package com.fedming.bottomnavigationdemo.mq;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fedming.bottomnavigationdemo.Call.MainActivity;
import com.fedming.bottomnavigationdemo.HomeActivity;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class MqConsumer {
    //常量：病床号，暂定为1
    public static String QUEUE_NUM = "";

    // 队列名设计：护士站编号-病床号
    public static String QUEUE_NAME = "";

    public static final String HEADERS_EXCHANGE = "bed";

    public static String CONNECTION_NAME = "Android Consumer bed";

    public static String STATION_ID = "0";

    public static ConnectionFactory factory;

    private static final String HOST = "10.19.0.2";

    private static final Integer PORT = 5672;

    private static final String USER_NAME = "dev";

    private static final String PASSWORD = "@dev123";

    private static final String VIRTUAL_HOST = "/medical";

    /**
     * mq客户端连接设置
     */
    public static void setupConnectionFactory() {
        factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);
    }

    /**
     * 接收服务器发送的消息
     */
    public static void basicConsume(final Handler handler) {

        try {
            // 创建mq连接
            Connection connection = factory.newConnection(CONNECTION_NAME);
            final Channel channel = connection.createChannel();
            // header模式绑定：护士站站id与队列的对应关系
            Map<String, Object> map = new HashMap<>();
            map.put("x-match", "all");
            map.put("stationId", STATION_ID);
            // mq的队列声明
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            // 建立队列与交换机的绑定关系
            channel.queueBind(QUEUE_NAME, HEADERS_EXCHANGE, "", map);
            //实现DefaultConsumer完成消息获取并消费
            channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    String msg = new String(body);
                    long deliveryTag = envelope.getDeliveryTag();
                    channel.basicAck(deliveryTag, false);
                    // 将消息封装到handlerMessage中返回
                    Message message = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", msg);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            });
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理不同类型mq消息通知
     */
    public static void handleMessage(String message) {
        JSONObject data = JSON.parseObject(message);
        String type = data.getString("type");
        JSONObject body = data.getJSONObject("body");
        //System.out.println("收到mq消息"+message);
        switch (type) {
            case "shout":
                if(body.containsKey("action")&&body.getString("action").equals("update")){
                    HomeActivity.ChangeSounds();
                    break;
                }
                JSONArray array = body.getJSONArray("beds");
                //自己不在通知范围内
                if (!array.contains(QUEUE_NUM))
                    break;
                String audioUrl = body.getString("url");
                System.out.println("开始播放");
                playVoice(audioUrl);
                break;
            case "others":
                //TODO: 其他通知类型
                break;
            default:
                break;
        }
    }


    /**
     * 播放地址音频
     */
    public static void playVoice(String url) {
        //TODO: 后台播放音频
        new Thread(new Runnable() {//使用子线程播放
            boolean isRelease = true;//设计暂停功能
            MediaPlayer mediaPlayer;
            @Override
            public void run() {

                if(url!=null) {
                    try {
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(url);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
                        mediaPlayer.prepare();
                        mediaPlayer.start();
//                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//
//                            @Override
//                            public void onPrepared(MediaPlayer mp) {
//                                if (isRelease){
//                                Log.e("MediaPlayer ","开始播放");
//                                mp.start();
//                                //isRelease = false;
//                                }
//                            }
//                        });
//                        {//有来电
//                            mediaPlayer.pause();
//                        }
//                        {//结束
//                            mediaPlayer.reset();     //重置MediaPlayer
//                            mediaPlayer.release();
//                            isRelease = true;
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                else
                    Log.e("MediaPlayer","地址错误");
            }
        }).start();

    }

}
